package first;

import java.io.*;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = null;
        try {
            serverSocket = new ServerSocket();
            serverSocket.bind(new InetSocketAddress(10001));
            System.out.println("server listen at 10001");
            Socket socket = serverSocket.accept();
            new ServerOne(socket);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            serverSocket.close();
        }
    }
}
class ServerOne extends Thread {
    private Socket s;
    private BufferedReader in;
    private PrintWriter out;
    public ServerOne(Socket s) throws IOException {
        this.s = s;
        in = new BufferedReader(new InputStreamReader(s.getInputStream()));
        out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(s.getOutputStream())), true);
        start();
    }
    public void run(){
        try {
            while(true) {
                String str = in.readLine();
                if(str.trim().equals("end")) break;
                System.out.println("Server: receive information "+str);
                int i = str.indexOf("+");
                if (i > 0 && i < (str.length() - 1)){
                    int a = Integer.parseInt(str.substring(0, i));
                    int b = Integer.parseInt(str.substring(i + 1));
                    out.println(a + b);
                }else {
                    out.println(0);
                }
            }
            System.out.println("server closing....");
        } catch (IOException e){
            e.printStackTrace();
        } finally {
            try{
                s.close();
            }catch(IOException e){}
        }
    }
}
